package simbot.example.listener;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import freemarker.template.TemplateException;
import love.forte.di.annotation.Beans;
import love.forte.simboot.annotation.Listener;
import love.forte.simbot.ID;
import love.forte.simbot.Identifies;
import love.forte.simbot.LongID;
import love.forte.simbot.component.mirai.bot.MiraiBot;
import love.forte.simbot.component.mirai.event.MiraiGroupMessageEvent;
import love.forte.simbot.component.mirai.event.MiraiReceivedMessageContent;
import love.forte.simbot.component.mirai.message.MiraiSendOnlyImage;
import love.forte.simbot.definition.Group;
import love.forte.simbot.definition.GroupMember;
import love.forte.simbot.event.GroupMessageEvent;
import love.forte.simbot.message.At;
import love.forte.simbot.resources.PathResource;
import love.forte.simbot.resources.Resource;

import love.forte.simbot.utils.item.Items;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;

import org.springframework.util.StringUtils;
import simbot.example.entity.*;
import simbot.example.mapper.*;
import simbot.example.util.*;
import simbot.example.util.HttpUtil;
import simbot.example.util.QuFuUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static simbot.example.util.GenerateImageUtil.generateSizeImage;
import static simbot.example.util.GenerateImageUtil.generateSizeImageJiaoYiHang;

/**
 * 群相关事件
 *
 * @author ForteScarlet
 */
@Beans
@Component
public class MyGroupListener {
    private static final Logger log = LoggerFactory.getLogger("群消息");
    private static final String robot = "添只饺子";
    public static List<Group> groupList = new ArrayList<>();

    /**
     * 这里监听的是mirai组件所提供的特殊事件类型: {@link MiraiGroupMessageEvent}
     * 一个组件的特殊事件能够提供更丰富的特性，并且更有针对性。
     * <p>
     * <p>
     * 此事件在控制台打印所有的群消息，不做其他操作。
     *
     * @param event 事件本体
     */
    @Listener
    public void myGroupListen(MiraiGroupMessageEvent event) throws IOException, InterruptedException, TemplateException {
        LongID id = event.getGroup().getId();
        long groupId = id.getNumber();
        GroupQu group = QuFuUtil.getGroup(groupId);
        String token = QuFuUtil.getParam("token").getValue();
        //判断是否存在
        if (!ObjectUtils.isEmpty(group)) {
            if ("1".equals(group.getDingshi()) && !groupList.contains(event.getGroup())) {
                groupList.add(event.getGroup());
            }
            MiraiReceivedMessageContent messageContent = event.getMessageContent();
            String plainText = messageContent.getPlainText();
            String[] text = plainText.split(" ");
            if ("奇遇".equals(text[0])) {
                qiyuListen(event, groupId);
            } else if ("小说".equals(text[0])) {
                xiaoShouListen(event, groupId);
            }else if ("宏".equals(text[0])) {
                hongListen(event, groupId);
            } else if ("骚话".equals(text[0])) {
                saohuaListen(event, groupId);
            }else if ("吃什么".equals(text[0])) {
                chiListen(event, groupId);
            }else if ("功能".equals(text[0])) {
                gongNengListen(event, groupId);
            } else if ("交易行".equals(text[0])) {
                jiaoYiHangListen(event, groupId);
            } else if ("搜索物品".equals(text[0])) {
                souSuoListen(event, groupId);
            } else if ("抓马".equals(text[0])) {
                zhuamaListen(event, groupId);
            } else if ("日常".equals(text[0])) {
                totalListen(event, groupId);
            } else if ("八卦".equals(text[0])) {
                baguaListen(event, groupId);
            } else if ("cd".equals(text[0]) || "CD".equals(text[0])) {
                cdListen(event, groupId, "cd", token);
            } else if ("配装".equals(text[0])) {
                peizhuangListen(event, groupId);
            } else if ("日常预测".equals(text[0])) {
                calendarListen(event, groupId);
            } else if ("金价".equals(text[0])) {
                if (text.length == 1) {
                    jinListen(event, groupId, "jin", null, token, null);
                } else {
                    jinListen(event, groupId, "jin", text[1], token, null);
                }
            } else if ("公告".equals(text[0])) {
                tongyongListen(event, groupId, "gonggao");
            } else if ("科举".equals(text[0])) {
                kejuListen(event, groupId);
            } else if ("鲜花".equals(text[0])) {
                if (text.length == 1) {
                    tongyongListen(event, groupId, "xianhua", null, null, null);
                } else {
                    tongyongListen(event, groupId, "xianhua", text[1], null, null);
                }
            } else if ("开服".equals(text[0])) {
                kaifuListen(event, groupId);
            } else if ("沙盘".equals(text[0])) {
                if (text.length == 1) {
                    tongyongListen(event, groupId, "shapan", null, token, null);
                } else {
                    tongyongListen(event, groupId, "shapan", text[1], token, null);
                }
            } else if ("奇遇统计".equals(text[0])) {
                if (text.length == 2) {
                    qiyutongjiListen(event, groupId, "qiyutongji", null, token, text[1]);
                } else {
                    qiyutongjiListen(event, groupId, "qiyutongji", text[2], token, text[1]);
                }
            } else if ("奇遇汇总".equals(text[0])) {
                if (text.length == 1) {
                    tongyongListen(event, groupId, "qiyuhuizong", null, token, null);
                } else {
                    tongyongListen(event, groupId, "qiyuhuizong", text[1], token, null);
                }
            } else if ("全服奇遇".equals(text[0])) {
                if (text.length == 2) {
                    quanfuqiyuListen(event, groupId, "quanfuqiyu", text[1], token);
                }
            } else if ("名剑".equals(text[0])) {
                mingjianListen(event, groupId, "mingjian");
            } else if ("名剑排行".equals(text[0])) {
                mingjianpaihangListen(event, groupId, "mingjianpaihang");
            } else if ("名剑统计".equals(text[0])) {
                mingjianpaihangListen(event, groupId, "mingjiantongji");
            } else if ("招募".equals(text[0])) {
                zhaomuListen(event, groupId, "zhaomu");
            } else if ("物价".equals(text[0])) {
                wujiaListen(event, groupId, "wujia", token, text[1]);
            } else if ("装备".equals(text[0])) {
                if (text.length == 3) {
                    zhuangbeiListen(event, groupId, "zhuangbei", text[1], token, text[2]);
                } else {
                    zhuangbeiListen(event, groupId, "zhuangbei", null, token, text[1]);
                }

            } else if ("微博".equals(text[0])) {
                weiboListen(event, groupId);
            } else if ("翻译".equals(text[0])) {
                fanyiListen(event, groupId);
            } else if ("制作".equals(text[0])) {
                biaoqingbaoListen(event, groupId);
            }
        }
    }

    //搜索物品查询
    public void souSuoListen(MiraiGroupMessageEvent event, long groupId) throws IOException {
        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");

        //获取mybatis
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3. 获取mapper
        WuPingMapper wuPingMapper = sqlSession.getMapper(WuPingMapper.class);

        //搜索物品
        Param param = QuFuUtil.getParam("souSuoWuPing");
        String s = HttpUtil.get(param.getValue() + "?keyword=" + text[1] + "&page=1&limit=15&client=std");
        final JSONObject json = JSONObject.parseObject(s);
        List<WuPing> collect = new ArrayList<>();
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            Map<String, Object> params = JSONObject.parseObject(json.toJSONString());
            Map<String, Object> data3 = (Map<String, Object>) params.get("data");
            JSONArray ja = (JSONArray) data3.get("data");
            collect = ja.toJavaList(WuPing.class);
            for (WuPing wuPing : collect) {
                String id = wuPing.getId();
                WuPing wuPing1 = wuPingMapper.selectById(id);
                if (ObjectUtils.isEmpty(wuPing1)) {
                    wuPingMapper.insertWuPing(wuPing);
                }
            }
            sqlSession.commit();
            if (collect.size() > 0) {
                List<String> collect1 = collect.stream().map(p -> p.getName()).collect(Collectors.toList());
                String join = String.join("/", collect1);
                event.getGroup().sendBlocking("你可能查询物品是 " + join);
            } else {
                event.getGroup().sendBlocking("查询不到物品");
            }
        }
        sqlSession.close();

    }

    /**
     * 功能
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void  gongNengListen(MiraiGroupMessageEvent event, long groupId) throws IOException, InterruptedException {
        String path="src/main/resources/gongneng/gongneng1.jpg";
        String path1="src/main/resources/gongneng/gongneng2.png";
        Random r = new Random();
        String address= r.nextBoolean() ? path1 : path;
        try {
            if (!StringUtils.isEmpty(address)) {
                //发送图片
                PathResource resource1 = Resource.of(Paths.get(address));
                MiraiSendOnlyImage sendOnlyImage = MiraiSendOnlyImage.of(resource1);
                sendOnlyImage.uploadBlocking(event.getGroup());
                event.getGroup().sendBlocking(sendOnlyImage);
            }
        }catch (Exception e) {
        }
    }
    /**
     * 小说查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void xiaoShouListen(MiraiGroupMessageEvent event, long groupId) throws IOException{
        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");

        Param param = QuFuUtil.getParam("xiaoshuo");
        String s = HttpUtil.getBase64FromUrl(param.getValue()+text[1]);
        Integer size=10;
        if(ObjectUtil.isNotEmpty("20")){
            size=Integer.parseInt("20");
        }
        JSONObject json = JSONObject.parseObject(s);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code"))) {
            JSONArray ja = (JSONArray) json.get("novels");
            List<Map> maps = ja.toJavaList(Map.class);
            if(maps.size()<size){
                size=maps.size();
            }

            String context="";
            for (Integer i = 0; i < size; i++) {
                context=context+ i+1+".书名："+maps.get(i).get("title")+"\n作者："+maps.get(i).get("author")+"\nurl："
                        +maps.get(i).get("url")+"\n";
            }
            event.getGroup().sendBlocking(context);
        }
    }

    /**
     * 吃啥
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void chiListen(MiraiGroupMessageEvent event, long groupId) throws IOException {
        Param param = QuFuUtil.getParam("chishenmo");
        String s = HttpUtil.get(param.getValue());
        JSONObject json = JSONObject.parseObject(s);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code"))) {
            event.getGroup().sendBlocking("1."+json.getString("meal1")+"\n"+"2."+json.getString("meal2")+"\n"+json.getString("mealwhat"));
            return;
        }
        //获取mybatis
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 获取mapper
        CaiMapper caiMapper = sqlSession.getMapper(CaiMapper.class);
        List<Cai> cai = caiMapper.selectOne();
        sqlSession.close();
        event.getGroup().sendBlocking("1."+cai.get(0).getName()+"\n"+"2."+cai.get(1).getName()+"\n"+"3."+cai.get(2).getName()
        );
    }

    //交易行查询
    public void jiaoYiHangListen(MiraiGroupMessageEvent event, long groupId) throws IOException {
        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        String result = "";
        String name = "";
        String size = "50";
        //是否输入长度
        GroupQu groupQu = QuFuUtil.getGroup(groupId);
        String fu = groupQu.getQu();
        name = text[1];
        if (text.length == 3) {
            size = text[2];
        }

        //获取mybatis
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3. 获取mapper
        WuPingMapper wuPingMapper = sqlSession.getMapper(WuPingMapper.class);
        List<WuPing> wuPings = wuPingMapper.selectByName(name);
        //搜索物品
        Param param = QuFuUtil.getParam("souSuoWuPing");
        String s = HttpUtil.get(param.getValue() + "?keyword=" + name + "&page=1&limit="+size+"&client=std");
        JSONObject json = JSONObject.parseObject(s);
        List<WuPing> collect = new ArrayList<>();
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            Map<String, Object> params = JSONObject.parseObject(json.toJSONString());
            Map<String, Object> data3 = (Map<String, Object>) params.get("data");
            JSONArray ja = (JSONArray) data3.get("data");
            collect = ja.toJavaList(WuPing.class);
            for (WuPing wuPing : collect) {
                String id = wuPing.getId();
                WuPing wuPing1 = wuPingMapper.selectById(id);
                if (ObjectUtils.isEmpty(wuPing1)) {
                    wuPingMapper.insertWuPing(wuPing);
                }
            }
            sqlSession.commit();
        }
        sqlSession.close();
        collect.addAll(wuPings);
        collect = collect.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(p -> p.getId()))), ArrayList::new));
        //搜索交易行
        if (collect.size() > 0) {
            List<Map<String, String>> list1 = new ArrayList<>();
            Map<String, String> map = new HashMap<>();
            map.put("0", fu);
            map.put("0", "");
            map.put("1", name);
            map.put("3", "");
            list1.add(map);

            for (int j = 0; j < collect.size(); j++) {
                result = HttpUtil.get("https://next2.jx3box.com/api/item-price/" + collect.get(j).getId() + "/detail?server=" + fu);
                JSONObject json1 = JSONObject.parseObject(result);
                if (!ObjectUtils.isEmpty(json1.getString("msg")) && "ok".equals(json1.getString("msg")) && !StringUtils.isEmpty(json1.getString("data"))) {
                    Map<String, Object> params = JSONObject.parseObject(json1.toJSONString());
                    Map<String, Object> data3 = (Map<String, Object>) params.get("data");
                    JSONArray ja = (JSONArray) data3.get("prices");
                    if (ObjectUtils.isEmpty(ja)) {
                        continue;
                    }
                    List<PricesDto> list = ja.toJavaList(PricesDto.class);
                    if (list.size() > 0) {
                        try {
                            if (collect.size() == 1) {
                                for (PricesDto pricesDto : list) {
                                    Map<String, String> map1 = new HashMap();
                                    map1.put("0", collect.get(j).getName());
                                    map1.put("1", pricesDto.getUnit_price() / 100000000 + " Z " + (pricesDto.getUnit_price() % 100000000) / 10000 + " J");
                                    map1.put("2", pricesDto.getN_count());
                                    Long time = pricesDto.getCreated();
                                    if (time == 0) {
                                        map1.put("3", "未知");
                                    } else {
                                        Date date = new Date(time * 1000);
                                        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        String time1 = sd.format(date);
                                        map1.put("3", time1);
                                    }
                                    list1.add(map1);
                                }
                            } else {
                                list = list.stream().sorted(Comparator.comparing(PricesDto::getUnit_price)).collect(Collectors.toList());
                                Map<String, String> map1 = new HashMap();
                                map1.put("0", collect.get(j).getName());
                                map1.put("1", list.get(0).getUnit_price() / 100000000 + " Z " + (list.get(0).getUnit_price() % 100000000) / 10000 + " J");
                                map1.put("2", list.get(0).getN_count());
                                Long time = list.get(0).getCreated();
                                if (time == 0) {
                                    map1.put("3", "未知");
                                } else {
                                    Date date = new Date(time * 1000);
                                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    String time1 = sd.format(date);
                                    map1.put("3", time1);
                                }
                                list1.add(map1);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            UUID uuid = UUID.randomUUID();
            String path = "src/main/resources/image/" + uuid.toString() + ".jpg";
            generateSizeImageJiaoYiHang(list1, path, "不要频繁发起查询哦！");
            //发送图片
            PathResource resource1 = Resource.of(Paths.get(path));
            MiraiSendOnlyImage sendOnlyImage = MiraiSendOnlyImage.of(resource1);
            event.getGroup().sendBlocking(sendOnlyImage);
            return;
        }
        event.getGroup().sendBlocking("查询不到物品 检查名称是否正确");
    }

    /**
     * 抓马监听
     *
     * @param event
     * @param groupId
     */
    public void zhuamaListen(MiraiGroupMessageEvent event, long groupId) throws IOException {
        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        //获取参数
        GroupQu group = QuFuUtil.getGroup(groupId);
        Param param = QuFuUtil.getParam("zhuama");
        String server = "";
        if (text.length == 2) {
            server = text[1];
        } else {
            server = group.getQu();
        }
        String url = param.getValue() + "?pageIndex=1&pageSize=50&server=" + server + "&type=horse";
        String result = HttpUtil.get(url);
        final JSONObject json = JSONObject.parseObject(result);
        String data = json.getString("data");
        final JSONObject json1 = JSONObject.parseObject(data);
        String list = json1.getString("list");
        List<ZhuaMaDto> zhuaMaDtoList = (List<ZhuaMaDto>) JSONArray.parseArray(list, ZhuaMaDto.class);

        String message = "";
        //获取时间戳(十分钟前的)
        long time = System.currentTimeMillis() - 60000 * 10;
        List<ZhuaMaDto> collect = zhuaMaDtoList.stream().filter(p -> "zhcn_hd".equals(p.getEdition()) && p.getTime() * 1000 > time).collect(Collectors.toList());
        //5-10分钟播报
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        for (ZhuaMaDto zhuaMaDto : collect) {
            long startTime = zhuaMaDto.getTime() * 1000 + 60000 * 5;
            long endTime = zhuaMaDto.getTime() * 1000 + 60000 * 10;
            String start = sdf.format(new Date(Long.parseLong(String.valueOf(startTime))));
            String end = sdf.format(new Date(Long.parseLong(String.valueOf(endTime))));
            String str = zhuaMaDto.getContent();
            String address = str.substring(str.indexOf("有宝马良驹在") + 6, str.lastIndexOf("出没！"));
            message = message + address + "将有宝马良驹出现   " + start + "~" + end + "\n";
        }

        //npcChat
        String yinShanDaCaoYuan = "阴山大草原马场：\n";
        ZhuaMaDto yinShan = zhuaMaDtoList.stream().filter(p -> "216".equals(p.getMap_id())).collect(Collectors.toList()).get(0);
        String[] split = yinShan.getContent().split("\n");
        for (String str : split) {
            if (str.contains("分钟")) {
                String horse = str.substring(str.indexOf("下一匹") + 3, str.lastIndexOf("出世"));
                String fenZhong = str.substring(str.indexOf("还有") + 2, str.lastIndexOf("分钟"));
                long startTime = yinShan.getTime() * 1000 + 60000 * (Long.parseLong(fenZhong) + 5);
                long endTime = yinShan.getTime() * 1000 + 60000 * (Long.parseLong(fenZhong) + 10);
                String start = sdf.format(new Date(Long.parseLong(String.valueOf(startTime))));
                String end = sdf.format(new Date(Long.parseLong(String.valueOf(endTime))));
                if (System.currentTimeMillis() < endTime) {
                    yinShanDaCaoYuan = yinShanDaCaoYuan + horse + "   时间" + start + "~" + end + "\n";
                }
            }
        }
        if (!"阴山大草原马场：\n".equals(yinShanDaCaoYuan)) {
            message = message + yinShanDaCaoYuan;
        }


        String heiGeBiMaChang = "黑戈壁马场：\n";
        ZhuaMaDto heiGeBi = zhuaMaDtoList.stream().filter(p -> "217".equals(p.getMap_id())).collect(Collectors.toList()).get(0);
        String[] split1 = heiGeBi.getContent().split("\n");
        for (String str : split1) {
            if (str.contains("分钟")) {
                String horse = str.substring(str.indexOf("下一匹") + 3, str.lastIndexOf("出世"));
                String fenZhong = str.substring(str.indexOf("还有") + 2, str.lastIndexOf("分钟"));
                long startTime = heiGeBi.getTime() * 1000 + 60000 * (Long.parseLong(fenZhong) + 5);
                long endTime = heiGeBi.getTime() * 1000 + 60000 * (Long.parseLong(fenZhong) + 10);
                String start = sdf.format(new Date(Long.parseLong(String.valueOf(startTime))));
                String end = sdf.format(new Date(Long.parseLong(String.valueOf(endTime))));
                if (System.currentTimeMillis() < endTime) {
                    heiGeBiMaChang = heiGeBiMaChang + horse + "   时间" + start + "~" + end + "\n";
                }
            }
        }
        if (!"黑戈壁马场：\n".equals(heiGeBiMaChang)) {
            message = message + heiGeBiMaChang;
        }
        if (ObjectUtils.isEmpty(message)) {
            event.getGroup().sendBlocking(server + "暂无抓马播报");
            return;
        }
        event.getGroup().sendBlocking(message);
    }

    /**
     * 骚话查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     * @throws InterruptedException
     */
    public void saohuaListen(MiraiGroupMessageEvent event, long groupId) throws IOException, InterruptedException {
        //获取mybatis
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 获取mapper
        SaoHuaMapper mapper = sqlSession.getMapper(SaoHuaMapper.class);
        SaoHua saoHua = mapper.selectByRandom();
        event.getGroup().sendBlocking(saoHua.getText());
    }

    /**
     * 宏
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void hongListen(MiraiGroupMessageEvent event, long groupId) throws IOException, InterruptedException {
        //获取mybatis
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 获取mapper
        MoHeDataMapper moHeDataMapper = sqlSession.getMapper(MoHeDataMapper.class);

        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        List<MoHeData> moHeData = moHeDataMapper.selectByZhiye("%" + text[1] + "%");
        if (moHeData.size() == 0) {
            event.getGroup().sendBlocking("查询失败 是不是语法错了 累了 毁灭吧");
        }
        for (MoHeData moHeDatum : moHeData) {
            event.getGroup().sendBlocking("心法:" + moHeDatum.getZhiye() + "     " + moHeDatum.getName() + "\n" + moHeDatum.getDesc() + "\n" + moHeDatum.getMacro() + "\n" + moHeDatum.getQixue());
            TimeUnit.SECONDS.sleep(5);
        }
        sqlSession.close();
    }

    // 表情包制作
    public void biaoqingbaoListen(MiraiGroupMessageEvent event, long groupId) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        HeChengMapper heChengMapper = sqlSession.getMapper(HeChengMapper.class);
        //获取消息成员
        List<String> avatarList =new ArrayList<>();
        Group group = event.getGroup();
        String avatar = event.getAuthor().getAvatar();
        avatarList.add(avatar);
        //获取被@成员
        String avatar1;
        for (var element : event.getMessageContent().getMessages()){
            if (element instanceof At at) {
                ID target = at.getTarget();
                avatar1 = group.getMember(target).getAvatar();
                avatarList.add(avatar1);
            }
        }

        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        String key = text[1].split("@")[0];

        UUID uuid = UUID.randomUUID();
        String path = "src/main/resources/image/" + uuid.toString();


        HeCheng heCheng = heChengMapper.selectByKey(key);
        String address = heCheng.getAddress();
        String type = heCheng.getType();
        String json = heCheng.getJson();
        int with = heCheng.getWith();
        int high = heCheng.getHigh();
        sqlSession.close();
        List<ZuoBiao> list = JSON.parseArray(json,ZuoBiao.class);
        path=path+"."+type;
        if ("gif".equals(type)) {

        }else {
            for (int i = 0; i < list.size(); i++) {
                with=ObjectUtil.isNotEmpty(list.get(i).getWith())?list.get(i).getWith():with;
                high=ObjectUtil.isNotEmpty(list.get(i).getHigh())?list.get(i).getHigh():high;
                if(with!=0&&high!=0) {
                    ImageServiceImpl.imageWatermark(avatarList.get(i), address, path,
                            Integer.parseInt(list.get(i).getX()), Integer.parseInt(list.get(i).getY()), 1, with, high);
                    address = path;
                }
            }
        }
        //发送图片
        PathResource resource1 = Resource.of(Paths.get(path));
        MiraiSendOnlyImage sendOnlyImage = MiraiSendOnlyImage.of(resource1);
        sendOnlyImage.uploadBlocking(event.getGroup());
        event.getGroup().sendBlocking(sendOnlyImage);
    }

    // 查询奇遇
    public void qiyuListen(MiraiGroupMessageEvent event, long groupId) throws IOException {
        String token = QuFuUtil.getParam("token").getValue();
        //获取mybatis
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 获取mapper
        ParamMapper paramMapper = sqlSession.getMapper(ParamMapper.class);

        Group group = event.getGroup();
        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        String result = "";
        String name = "";
        String fu = "";
        Param param = paramMapper.selectById("qiYuUrl");
        //是否输入区服
        if (text.length == 2) {
            GroupQuMapper groupQumapper = sqlSession.getMapper(GroupQuMapper.class);
            GroupQu groupQu = groupQumapper.selectById(groupId);
            fu = groupQu.getQu();
            name = text[1];
            result = HttpUtil.get(param.getValue() + "?server=" + fu + "&name=" + name + "&token=" + token);
        }
        if (text.length == 3) {
            name = text[2];
            fu = text[1];
            result = HttpUtil.get(param.getValue() + "?server=" + fu + "&name=" + name + "&token=" + token);
        }
        //4. 释放资源
        sqlSession.close();

        if (!StringUtils.isEmpty(result)) {
            final JSONObject json = JSONObject.parseObject(result);
            if (StringUtils.isEmpty(json.getString("data"))) {
                event.getGroup().sendBlocking(fu + "的" + name + "侠士查询不到奇遇，请继续努力");
                return;
            }
            if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
                JSONArray ja = json.getJSONArray("data");
                List<QiYuDto> collect = ja.toJavaList(QiYuDto.class);
                List<QiYuDto> list = collect.stream().filter(p -> !"3".equals(p.getLevel())).collect(Collectors.toList());
                if (list.size() == 0) {
                    event.getGroup().sendBlocking(fu + "的" + name + "侠士查询不到奇遇，请继续努力");
                }
                try {
                    String[][] tableData2 = new String[list.size() + 1][3];
                    tableData2[0][0] = fu;
                    tableData2[0][1] = name;
                    for (int i = 0; i < list.size(); i++) {
                        tableData2[i + 1][0] = list.get(i).getName();
                        tableData2[i + 1][1] = list.get(i).getEvent();
                        Long time = list.get(i).getTime();
                        if (time == 0) {
                            tableData2[i + 1][2] = "未知";
                        } else {
                            Date date = new Date(time * 1000);
                            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String time1 = sd.format(date);
                            tableData2[i + 1][2] = time1;
                        }
                    }
                    UUID uuid = UUID.randomUUID();
                    String path = "src/main/resources/image/" + uuid.toString() + ".jpg";
                    generateSizeImage(tableData2, path, "不要频繁发起查询哦！");
                    //发送图片
                    PathResource resource1 = Resource.of(Paths.get(path));
                    MiraiSendOnlyImage sendOnlyImage = MiraiSendOnlyImage.of(resource1);
                    sendOnlyImage.uploadBlocking(event.getGroup());
                    event.getGroup().sendBlocking(sendOnlyImage);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                group.sendBlocking("查询失败 累了 毁灭吧");
            }
        } else {
            group.sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * cd查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void cdListen(MiraiGroupMessageEvent event, long groupId, String para, String token) throws IOException, TemplateException {
        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        String server = "";
        String name = "";
        if (text.length == 3) {
            server = text[1];
            name = text[2];
        }
        if (text.length == 2) {
            name = text[1];
            GroupQu group = QuFuUtil.getGroup(groupId);
            if (!ObjectUtils.isEmpty(group)) {
                server = group.getQu();
            }
        }
        //获取参数
        Param param = QuFuUtil.getParam(para);
        Param ticket = QuFuUtil.getParam("ticket");
        String url = param.getValue() + "?&token=" + token + "&server=" + server + "&ticket=" + ticket.getValue() + "&name=" + name;
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            Map<String, Object> dict = JSON.parseObject(json.getString("data"), Map.class);
            if (ObjectUtil.isNotEmpty(dict.get("data"))) {
                List<Map> list = JSON.parseArray(dict.get("data").toString(), Map.class);
                for (Map map : list) {
                    String finBoss = "";
                    String unBoss = "";
                    if (ObjectUtil.isNotEmpty(map.get("bossProgress"))) {
                        List<Map> list1 = JSON.parseArray(map.get("bossProgress").toString(), Map.class);
                        for (Map map1 : list1) {
                            String s = map1.get("finished").toString();
                            if ("true".equals(map1.get("finished").toString())) {
                                finBoss = finBoss + "-" + map1.get("name");
                            } else {
                                unBoss = unBoss + "/" + map1.get("name");
                            }
                        }
                    }
                    map.put("finBoss", finBoss);
                    map.put("unBoss", unBoss);
                }
                dict.put("data", list);
            }
            //生成图片
            ModelMap modelMap = new ModelMap();
            modelMap.put("resume", dict);
            String templateName = "cd.ftl";
            String html = FreemarkeTools.ftlToString(modelMap, templateName);
            String htmlFilePath = "src/main/resources/html/resume.html";
            UUID uuid = UUID.randomUUID();
            String imageFilePath = "src/main/resources/image/" + uuid.toString() + ".png";
            String imgPath = FreemarkeTools.turnImage(html, htmlFilePath, imageFilePath, 1000, 600);
            // 构建图片
            PathResource resource1 = Resource.of(Paths.get(imgPath));
            MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(resource1);
            event.getGroup().sendBlocking(offlineImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * 配装查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void peizhuangListen(MiraiGroupMessageEvent event, long groupId) throws IOException {
        //获取mybatis
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3. 获取mapper
        PeiZhuangMapper peiZhuangMapper = sqlSession.getMapper(PeiZhuangMapper.class);
        Group group = event.getGroup();
        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        String zhiye = "";
        String type = "";
        //是否输入区服
        if (text.length == 2) {
            zhiye = text[1];
            type = "PVP";
        }
        if (text.length == 3) {
            zhiye = text[1];
            String s = text[2];
            type = s.toUpperCase();
        }

        PeiZhuang peiZhuang = peiZhuangMapper.selectByTypeZhiye(type, zhiye);
        sqlSession.close();
        if (!StringUtils.isEmpty(peiZhuang)) {
            //发送图片
            PathResource resource1 = Resource.of(Paths.get(peiZhuang.getPath()));
            MiraiSendOnlyImage sendOnlyImage = MiraiSendOnlyImage.of(resource1);
            sendOnlyImage.uploadBlocking(event.getGroup());
            event.getGroup().sendBlocking(sendOnlyImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * 八卦查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void baguaListen(GroupMessageEvent event, long groupId) throws IOException {
        String token = QuFuUtil.getParam("token").getValue();
        String[] ci = {"818", "616", "树洞", "记录", "教程", "街拍", "故事", "避雷", "吐槽", "提问"};
        Group group1 = event.getGroup();
        //获取参数
        Param param = QuFuUtil.getParam("bagua");
        //获取消息
        MiraiReceivedMessageContent messageContent = (MiraiReceivedMessageContent) event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        String server1 = "";
        String type1 = RandomUtil.randomEle(ci);
        if (text.length > 1) {
            type1 = text[1];
        }
        if (text.length == 3) {
            server1 = text[1];
            type1 = text[2];
        }
        String result = HttpUtil.get(param.getValue() + "?&token=" + token + "&server=" + server1 + "&subclass=" + type1 + "&limit=1");
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            String type = "";
            String server = "";
            String title = "";
            String url = "";
            List<Map> list = JSONArray.parseArray(json.getString("data"), Map.class);
            for (Map map : list) {
                type = map.get("subclass").toString();
                server = map.get("server").toString();
                title = map.get("title").toString();
                url = "https://tieba.baidu.com/p/" + map.get("url").toString() + "?frwh=index";
            }
            group1.sendBlocking(server + "--[" + type + "]" + "\n" +
                    title + "\n" +
                    url);
        } else {
            group1.sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * 日常查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void totalListen(GroupMessageEvent event, long groupId) throws IOException {
        Group group1 = event.getGroup();
        //获取参数
        GroupQu group = QuFuUtil.getGroup(groupId);
        Param param = QuFuUtil.getParam("total");
        //获取消息
        MiraiReceivedMessageContent messageContent = (MiraiReceivedMessageContent) event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        int num = 0;
        String qu = group.getQu();
        if (text.length > 1) {
            if ("明天".equals(text[1])) {
                num = 1;
            } else if ("后天".equals(text[1])) {
                num = 2;
            }
        }
        if (text.length == 3) {
            qu = text[2];
        }
        String result = HttpUtil.get(param.getValue() + "?server=" + qu + "&num=" + num);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            TotalDto totalDto = json.getObject("data", TotalDto.class);
            String[] split = totalDto.getDate().split("-");
            //家园声望
            String pre = "";
            if (ObjectUtil.isNotEmpty(totalDto.getPrestige())) {
                String[] prestige = totalDto.getPrestige();
                pre = String.join("、", prestige);
            }
            //武林通鉴
            String[] team = totalDto.getTeam();
            String team1 = String.join("\n", team);
            //美人图
            String huatu = "";
            if (!ObjectUtils.isEmpty(totalDto.getHuatu())) {
                huatu = "美人图∶" + totalDto.getHuatu() + "\n";
            }

            group1.sendBlocking("今天是" + split[0] + "年" + split[1] + "月" + split[2] + "日星期" + totalDto.getWeek() + "\n" +
                    "阵营∶跨服·烂柯山\n" +
                    "战场∶" + totalDto.getBattle() + "\n" +
                    "大战∶" + totalDto.getWar() + "\n" +
                    "家园声望∶" + pre + "\n" +
                    "武林通鉴∶" + team1 + "\n"
                    + huatu +
                    "活动∶" + totalDto.getSchool());
        } else {
            group1.sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * 科举查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void kejuListen(GroupMessageEvent event, long groupId) throws IOException {
        Group group1 = event.getGroup();
        //获取参数
        Param param = QuFuUtil.getParam("keju");
        //获取消息
        MiraiReceivedMessageContent messageContent = (MiraiReceivedMessageContent) event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        String result = HttpUtil.get(param.getValue() + "?match=" + text[1] + "&limit=" + 10);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            JSONArray ja = json.getJSONArray("data");
            List<KeJuDato> collect = ja.toJavaList(KeJuDato.class);
            if (collect.size() == 0) {
                group1.sendBlocking("查询不到");
                return;
            }
            String keju = "";
            for (KeJuDato keJuDato : collect) {
                keju = keju + keJuDato.getQuestion() + "  " + keJuDato.getAnswer() + "\n";
            }
            group1.sendBlocking(keju);
        } else {
            group1.sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * 开服查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void kaifuListen(GroupMessageEvent event, long groupId) throws IOException {
        Group group1 = event.getGroup();
        //获取参数
        Param param = QuFuUtil.getParam("kaifu");
        //获取消息
        MiraiReceivedMessageContent messageContent = (MiraiReceivedMessageContent) event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        String server = "";
        if (text.length == 2) {
            server = text[1];
        }
        if (StringUtils.isEmpty(server)) {
            GroupQu group = QuFuUtil.getGroup(groupId);
            if (!ObjectUtils.isEmpty(group)) {
                server = group.getQu();
            }
        } else if ("全服".equals(server)) {
            server = "";
        }
        String result = HttpUtil.get(param.getValue() + "?server=" + server);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            KaiFuDto kaiFuDto = json.getObject("data", KaiFuDto.class);
            String kaifu = "";
            if ("1".equals(kaiFuDto.getStatus())) {
                kaifu = kaifu + kaiFuDto.getServer() + "  " + "开服" + "\n";
            } else {
                kaifu = kaifu + kaiFuDto.getServer() + "  " + "维护" + "\n";
            }
            group1.sendBlocking(kaifu);
        } else {
            group1.sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * 活动日历
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void calendarListen(MiraiGroupMessageEvent event, long groupId) throws IOException {
        //获取参数
        Param param = QuFuUtil.getParam("calendar");
        String result = HttpUtil.get(param.getValue() + "?scale=1&robot=添只饺子&cache=1");
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            ImageDto imageDto = json.getObject("data", ImageDto.class);
            // 构建图片
            MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(imageDto.getUrl())));
            offlineImage.uploadBlocking(event.getGroup());
            event.getGroup().sendBlocking(offlineImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * 全服奇遇查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void zhaomuListen(MiraiGroupMessageEvent event, long groupId, String para) throws IOException {
        String token = QuFuUtil.getParam("token").getValue();
        GroupQu group = QuFuUtil.getGroup(groupId);
        //获取参数
        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        String server = "";
        String keyword = "";
        if (text.length == 2) {
            keyword = text[1];
            server = group.getQu();
        }
        if (text.length == 3) {
            server = text[1];
            keyword = text[2];
        }
        //获取参数
        Param param = QuFuUtil.getParam(para);
        Param ticket = QuFuUtil.getParam("ticket");
        String url = param.getValue() + "?scale=1&robot=" + robot + "&cache=1" + "&token=" + token + "&server=" + server + "&keyword=" + keyword + "&ticket=" + ticket.getValue();
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            ImageDto imageDto = json.getObject("data", ImageDto.class);
            // 构建图片
            MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(imageDto.getUrl())));
            offlineImage.uploadBlocking(event.getGroup());
            event.getGroup().sendBlocking(offlineImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * 全服奇遇查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void quanfuqiyuListen(MiraiGroupMessageEvent event, long groupId, String para, String name, String token) throws IOException {
        //获取参数
        Param param = QuFuUtil.getParam(para);
        String url = param.getValue() + "?scale=1&robot=" + robot + "&token=" + token + "&name=" + name;
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            ImageDto imageDto = json.getObject("data", ImageDto.class);
            // 构建图片
            MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(imageDto.getUrl())));
            offlineImage.uploadBlocking(event.getGroup());
            event.getGroup().sendBlocking(offlineImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * 名剑排行
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void mingjianpaihangListen(MiraiGroupMessageEvent event, long groupId, String para) throws IOException {
        String token = QuFuUtil.getParam("token").getValue();
        Param ticket = QuFuUtil.getParam("ticket");
        //获取参数
        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        String mode = "";
        if (text.length == 2) {
            mode = text[1];
        }
        Param param = QuFuUtil.getParam(para);
        String url = "";
        if (ObjectUtils.isEmpty(mode)) {
            url = param.getValue() + "?scale=1&robot=" + robot + "&cache=1" + "&token=" + token + "&ticket=" + ticket.getValue();
        } else {
            url = param.getValue() + "?scale=1&robot=" + robot + "&cache=1" + "&token=" + token + "&ticket=" + ticket.getValue() + "&mode=" + mode;
        }
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            ImageDto imageDto = json.getObject("data", ImageDto.class);
            // 构建图片
            MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(imageDto.getUrl())));
            offlineImage.uploadBlocking(event.getGroup());
            event.getGroup().sendBlocking(offlineImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * 名剑查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void
    mingjianListen(MiraiGroupMessageEvent event, long groupId, String para) throws IOException {
        GroupQu group = QuFuUtil.getGroup(groupId);
        String token = QuFuUtil.getParam("token").getValue();
        Param ticket = QuFuUtil.getParam("ticket");
        //获取参数
        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String plainText = messageContent.getPlainText();
        String[] text = plainText.split(" ");
        String name = "";
        String server = "";
        String mode = "";
        if (text.length == 4) {
            server = text[1];
            name = text[2];
            mode = text[3];
        }
        if (text.length == 3) {
            if ("22".equals(text[2]) || "33".equals(text[2]) || "55".equals(text[2])) {
                name = text[1];
                mode = text[2];
                if (!ObjectUtils.isEmpty(group)) {
                    server = group.getQu();
                }
            } else {
                server = text[1];
                name = text[2];
            }
        }
        if (text.length == 2) {
            name = text[1];
            if (!ObjectUtils.isEmpty(group)) {
                server = group.getQu();
            }
        }
        Param param = QuFuUtil.getParam(para);
        String url = "";
        if (ObjectUtils.isEmpty(mode)) {
            url = param.getValue() + "?scale=1&robot=" + robot + "&server=" + server + "&token=" + token + "&name=" + name + "&ticket=" + ticket.getValue();
        } else {
            url = param.getValue() + "?scale=1&robot=" + robot + "&server=" + server + "&token=" + token + "&name=" + name + "&ticket=" + ticket.getValue() + "&mode=" + mode;
        }
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            ImageDto imageDto = json.getObject("data", ImageDto.class);
            // 构建图片
            MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(imageDto.getUrl())));
            offlineImage.uploadBlocking(event.getGroup());
            event.getGroup().sendBlocking(offlineImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    // /**
    //  * 名剑查询
    //  *
    //  * @param event
    //  * @param groupId
    //  * @throws IOException
    //  */
    // public void
    // mingjianListen(MiraiGroupMessageEvent event, long groupId, String para) throws IOException, TemplateException {
    //     String token = QuFuUtil.getParam("token").getValue();
    //     GroupQu group = QuFuUtil.getGroup(groupId);
    //     Param ticket = QuFuUtil.getParam("ticket");
    //     //获取参数
    //     MiraiReceivedMessageContent messageContent = event.getMessageContent();
    //     String plainText = messageContent.getPlainText();
    //     String[] text = plainText.split(" ");
    //     String name = "";
    //     String server = "";
    //     String mode = "";
    //     if (text.length == 4) {
    //         server = text[1];
    //         name = text[2];
    //         mode = text[3];
    //     }
    //     if (text.length == 3) {
    //         if ("22".equals(text[2]) || "33".equals(text[2]) || "55".equals(text[2])) {
    //             name = text[1];
    //             mode = text[2];
    //             if (!ObjectUtils.isEmpty(group)) {
    //                 server = group.getQu();
    //             }
    //         } else {
    //             server = text[1];
    //             name = text[2];
    //         }
    //     }
    //     if (text.length == 2) {
    //         name = text[1];
    //         if (!ObjectUtils.isEmpty(group)) {
    //             server = group.getQu();
    //         }
    //     }
    //     Param param = QuFuUtil.getParam(para);
    //     String url = "";
    //     if (ObjectUtils.isEmpty(mode)) {
    //         url = param.getValue() + "?&token=" + token+ "&server=" + server + "&ticket=" + ticket.getValue() + "&name=" + name;
    //     } else {
    //         url = param.getValue() + "?&token=" + token+ "&server=" + server + "&ticket=" + ticket.getValue() + "&name=" + name+"&mode=" + mode;
    //     }
    //     String result = HttpUtil.get(url);
    //     //返回参数处理
    //     final JSONObject json = JSONObject.parseObject(result);
    //     if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
    //         Map<String, Object> dict = JSON.parseObject(json.getString("data"), Map.class);
    //         if (ObjectUtil.isNotEmpty(dict.get("performance"))) {
    //             Map<String, Object> dict1 = JSON.parseObject(dict.get("performance").toString(), Map.class);
    //             dict.put("san",dict1.get("3v3"));
    //             dict.put("wu",dict1.get("5v5"));
    //             dict.put("er",dict1.get("2v2"));
    //         }
    //         if(StringUtils.isEmpty(dict.get("san"))){
    //             dict.put("san",new HashMap<>());
    //         }
    //         if(StringUtils.isEmpty(dict.get("er"))){
    //             dict.put("er",new HashMap<>());
    //         }
    //         if(StringUtils.isEmpty(dict.get("wu"))){
    //             dict.put("wu",new HashMap<>());
    //         }
    //         List<Map> list = JSON.parseArray(dict.get("history").toString(), Map.class);
    //         for (Map map : list) {
    //             Long startTime = Long.parseLong(map.get("startTime").toString());
    //             Long endTime = Long.parseLong(map.get("endTime").toString());
    //             Long time = endTime - startTime;
    //             map.put("time",time);
    //             Date date = new Date(endTime * 1000);
    //             SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //             String time1 = sd.format(date);
    //             map.put("endDay", time1);
    //             String won="";
    //             if("true".equals(map.get("won").toString())){
    //                 won="胜利";
    //             }else {
    //                 won="失败";
    //             }
    //             if("true".equals(map.get("mvp").toString())){
    //                 won=won+":mvp";
    //             }
    //             map.put("result",won);
    //         }
    //         dict.put("history",list);
    //         //生成图片
    //         ModelMap modelMap = new ModelMap();
    //         modelMap.put("resume", dict);
    //         String templateName = "mingjian.ftl";
    //         String html = FreemarkeTools.ftlToString(modelMap, templateName);
    //         String htmlFilePath = "src/main/resources/html/mingjian.html";
    //         UUID uuid = UUID.randomUUID();
    //         String imageFilePath = "src/main/resources/image/" + uuid.toString() + ".png";
    //         String imgPath = FreemarkeTools.turnImage(html, htmlFilePath, imageFilePath, 1000, 1000);
    //         // 构建图片
    //         PathResource resource1 = Resource.of(Paths.get(imgPath));
    //         MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(resource1);
    //         offlineImage.uploadBlocking(event.getGroup());
    //         event.getGroup().sendBlocking(offlineImage);
    //     } else {
    //         event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
    //     }
    // }

    /**
     * 奇遇统计查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void qiyutongjiListen(MiraiGroupMessageEvent event, long groupId, String para, String server, String token, String name) throws IOException {
        if (StringUtils.isEmpty(server)) {
            GroupQu group = QuFuUtil.getGroup(groupId);
            if (!ObjectUtils.isEmpty(group)) {
                server = group.getQu();
            }
        }
        //获取参数
        Param param = QuFuUtil.getParam(para);
        String url = param.getValue() + "?scale=1&robot=" + robot + "&cache=1" + "&server=" + server + "&token=" + token + "&name=" + name;
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            ImageDto imageDto = json.getObject("data", ImageDto.class);
            // 构建图片
            MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(imageDto.getUrl())));
            offlineImage.uploadBlocking(event.getGroup());
            event.getGroup().sendBlocking(offlineImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /**
     * 装备查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void zhuangbeiListen(MiraiGroupMessageEvent event, long groupId, String para, String server, String token, String name) throws IOException {
        if (StringUtils.isEmpty(server)) {
            GroupQu group = QuFuUtil.getGroup(groupId);
            if (!ObjectUtils.isEmpty(group)) {
                server = group.getQu();
            }
        }
        //获取参数
        Param param = QuFuUtil.getParam(para);
        Param ticket = QuFuUtil.getParam("ticket");
        String url = param.getValue() + "?scale=1&robot=" + robot + "&cache=1" + "&server=" + server + "&token=" + token + "&name=" + name + "&ticket=" + ticket.getValue();
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            ImageDto imageDto = json.getObject("data", ImageDto.class);
            // 构建图片
            MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(imageDto.getUrl())));
            offlineImage.uploadBlocking(event.getGroup());
            event.getGroup().sendBlocking(offlineImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }


    /**
     * 物价查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void wujiaListen(MiraiGroupMessageEvent event, long groupId, String para, String token, String name) throws IOException {
        //获取参数
        Param param = QuFuUtil.getParam(para);
        String url = param.getValue() + "?scale=1&robot=" + robot + "&cache=1" + "&token=" + token + "&name=" + name;
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            ImageDto imageDto = json.getObject("data", ImageDto.class);
            // 构建图片
            MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(imageDto.getUrl())));
            offlineImage.uploadBlocking(event.getGroup());
            event.getGroup().sendBlocking(offlineImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    // /**
    //  * 物价查询
    //  *
    //  * @param event
    //  * @param groupId
    //  * @throws IOException
    //  */
    // public void wujiaListen(MiraiGroupMessageEvent event, long groupId, String para, String token, String name) throws IOException, TemplateException {
    //     //获取参数
    //     Param param = QuFuUtil.getParam(para);
    //     String url = param.getValue() + "?&token=" + token + "&name=" + name;
    //     String result = HttpUtil.get(url);
    //     //返回参数处理
    //     final JSONObject json = JSONObject.parseObject(result);
    //     if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
    //         Map<String, Object> dict = JSON.parseObject(json.getString("data"), Map.class);
    //         List<Map<String,Object>> li=new ArrayList<>();
    //         if (ObjectUtil.isNotEmpty(dict.get("data"))) {
    //             List data = JSON.parseObject(dict.get("data").toString(), List.class);
    //             for (Object datum : data) {
    //                 List<Map> list = JSONArray.parseArray(datum.toString(), Map.class);
    //                 if(ObjectUtil.isNotEmpty(list)&&list.size()>0){
    //                     Map<String,Object> map=new HashMap<>();
    //                     map.put("name",list.get(0).get("class"));
    //                     map.put("list",list);
    //                     li.add(map);
    //                 }
    //                 for (Map map1 : list) {
    //                     if("1".equals(map1.get("sales").toString())){
    //                         map1.put("sales","出售");
    //                     }else if("2".equals(map1.get("sales").toString())){
    //                         map1.put("sales","收购");
    //                     }else if("3".equals(map1.get("sales").toString())){
    //                         map1.put("sales","想出");
    //                     }else if("4".equals(map1.get("sales").toString())){
    //                         map1.put("sales","想收");
    //                     }else if("5".equals(map1.get("sales").toString())){
    //                         map1.put("sales","成交");
    //                     } else if("6".equals(map1.get("sales").toString())){
    //                         map1.put("sales","正出");
    //                     }else if("7".equals(map1.get("sales").toString())){
    //                         map1.put("sales","公示");
    //                     }
    //                 }
    //             }
    //         }
    //         dict.put("li1",li.subList(0,li.size()/2));
    //         dict.put("li2",li.subList(li.size()/2,li.size()));
    //         //生成图片
    //         ModelMap modelMap = new ModelMap();
    //         modelMap.put("resume", dict);
    //         String templateName = "wujia.ftl";
    //         String html = FreemarkeTools.ftlToString(modelMap, templateName);
    //         String htmlFilePath = "src/main/resources/html/wujia.html";
    //         UUID uuid = UUID.randomUUID();
    //         String imageFilePath = "src/main/resources/image/" + uuid.toString() + ".jpg";
    //         String imgPath = FreemarkeTools.turnImage(html, htmlFilePath, imageFilePath, 800, 1300);
    //         // 构建图片
    //         PathResource resource1 = Resource.of(Paths.get(imgPath));
    //         MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(resource1);
    //         event.getGroup().sendBlocking(offlineImage);
    //     } else {
    //         event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
    //     }
    // }

    /**
     * 通用查询
     *
     * @param event
     * @param groupId
     * @throws IOException
     */
    public void tongyongListen(MiraiGroupMessageEvent event, long groupId, String para, String server, String token, String name) throws IOException {
        if (StringUtils.isEmpty(server)) {
            GroupQu group = QuFuUtil.getGroup(groupId);
            if (!ObjectUtils.isEmpty(group)) {
                server = group.getQu();
            }
        }
        //获取参数
        Param param = QuFuUtil.getParam(para);
        String url = "";
        if (!StringUtils.isEmpty(token)) {
            url = param.getValue() + "?scale=1&robot=" + robot + "&cache=1" + "&server=" + server + "&token=" + token + "&name" + name;
        } else {
            url = param.getValue() + "?scale=1&robot=" + robot + "&cache=1" + "&server=" + server;
        }
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            ImageDto imageDto = json.getObject("data", ImageDto.class);
            // 构建图片
            MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(imageDto.getUrl())));
            offlineImage.uploadBlocking(event.getGroup());
            event.getGroup().sendBlocking(offlineImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    public void tongyongListen(MiraiGroupMessageEvent event, long groupId, String para) throws IOException {
        //获取参数
        Param param = QuFuUtil.getParam(para);
        String result = HttpUtil.get(param.getValue() + "?scale=1&robot=" + robot + "&cache=1");
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            ImageDto imageDto = json.getObject("data", ImageDto.class);
            // 构建图片
            MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(imageDto.getUrl())));
            offlineImage.uploadBlocking(event.getGroup());
            event.getGroup().sendBlocking(offlineImage);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    /*
     *金价查询
     */
    public void jinListen(MiraiGroupMessageEvent event, long groupId, String para, String server, String token, String name) throws IOException, TemplateException {
        if (StringUtils.isEmpty(server)) {
            GroupQu group = QuFuUtil.getGroup(groupId);
            if (!ObjectUtils.isEmpty(group)) {
                server = group.getQu();
            }
        }
        //获取参数
        Param param = QuFuUtil.getParam(para);
        String url = param.getValue() + "?server=" + server + "&limit=2"+"&token="+token;
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            List<Map> list = JSON.parseArray(json.getString("data").toString(), Map.class);
            String jin = server + "金价：";
            for (Map map : list) {
                if (ObjectUtil.isNotEmpty(map.get("wanbaolou"))) {
                    jin = jin + "\n" + "万宝楼：" + map.get("wanbaolou").toString();
                }
                if (ObjectUtil.isNotEmpty(map.get("tieba"))) {
                    jin = jin + "\n" + "贴吧：" + map.get("tieba").toString();
                }
                if (ObjectUtil.isNotEmpty(map.get("dd373"))) {
                    jin = jin + "\n" + "dd373：" + map.get("dd373").toString();
                }
                if (ObjectUtil.isNotEmpty(map.get("5173"))) {
                    jin = jin + "\n" + "5173：" + map.get("5173").toString();
                }
                if (ObjectUtil.isNotEmpty(map.get("uu898"))) {
                    jin = jin + "\n" + "uu898：" + map.get("uu898").toString();
                }
                break;
            }
            event.getGroup().sendBlocking(jin);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    public void seTuListen(MiraiGroupMessageEvent event, long groupId) throws IOException {
        GroupQu group = QuFuUtil.getGroup(groupId);
        if ("1".equals(group.getSetu())) {
            MiraiReceivedMessageContent messageContent = event.getMessageContent();
            String plainText = messageContent.getPlainText();
            String[] text = plainText.split(" ");
            String chengdu = "0";
            if (text.length == 2 && "18".equals(text[1])) {
                chengdu = "1";
            }
            //获取参数
            Param param = QuFuUtil.getParam("setu");
            String result = HttpUtil.get(param.getValue() + "?r18=" + chengdu);
            //返回参数处理
            final JSONObject json = JSONObject.parseObject(result);
            if (!StringUtils.isEmpty(json.getString("data"))) {
                String list = json.getString("data");
                List<SeTu> zhuaMaDtoList = (List<SeTu>) JSONArray.parseArray(list, SeTu.class);
                for (SeTu seTu : zhuaMaDtoList) {
                    Map<String, String> urls = seTu.getUrls();
                    String url = urls.get("original");
                    MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(url)));
                    offlineImage.uploadBlocking(event.getGroup());
                    event.getGroup().sendBlocking(offlineImage);
                }
            } else {
                event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
            }
        } else {
            return;
        }
    }

    public void weiboListen(MiraiGroupMessageEvent event, long groupId) throws IOException {
        //获取参数
        Param param = QuFuUtil.getParam("weibo");
        String s = HttpRequest.sendGet(param.getValue(), null);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(s);
        if (!StringUtils.isEmpty(json.getString("success")) && json.getString("success").equals("true") && !StringUtils.isEmpty(json.getString("data"))) {
            String list = json.getString("data");
            List<WeiBo> zhuaMaDtoList = (List<WeiBo>) JSONArray.parseArray(list, WeiBo.class);
            String text = "微博热搜：";
            for (int i = 0; i < 15; i++) {
                text = text + "\n" + (i + 1) + ":" + zhuaMaDtoList.get(i).getTitle();
            }
            event.getGroup().sendBlocking(text);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }

    public void fanyiListen(MiraiGroupMessageEvent event, long groupId) throws IOException {
        MiraiReceivedMessageContent messageContent = event.getMessageContent();
        String wenben = messageContent.getPlainText();
        String substring = wenben.substring(3, wenben.length());
        String s1 = substring.replaceAll(" ", "%20");
        //获取参数
        Param param = QuFuUtil.getParam("fanyi");
        String s = HttpRequest.sendGet(param.getValue(), "text=" + s1);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(s);
        if (!StringUtils.isEmpty(json.getString("success")) && json.getString("success").equals("true") && !StringUtils.isEmpty(json.getString("data"))) {
            String data = json.getString("data");
            final JSONObject json1 = JSONObject.parseObject(data);
            String fanyi = json1.getString("fanyi");
            event.getGroup().sendBlocking(fanyi);
        } else {
            event.getGroup().sendBlocking("查询失败 累了 毁灭吧");
        }
    }
}
